import {Injectable} from "@angular/core";
import {Platform} from "ionic-angular";
import {Observable} from "rxjs/Observable";
// import {EncryptService} from "./encrypt.service";
// import {Config} from "../config/config";
import {Storage} from "@ionic/storage";
declare var DXPDFViewer: any;
declare var InAppBrowserWithHeader: any;

@Injectable()
export class PDFService {
  constructor(public platform: Platform,
            // public encrypt: EncryptService,
            //   public config: Config,
              public storage: Storage) {
  }

  public showPDFFile(pdf) {
    if (!pdf || !pdf['attachmentId']) {
      return;
    }
    if (this.platform.is('android')) {
      this.android(pdf);
    } else if (this.platform.is('ios')) {
      this.ios(pdf);
    } else {
      this.otherPlatform(pdf);
    }
  }

  private ios(pdf) {
    let url = 'www.baidu.com';
    InAppBrowserWithHeader.open(url, '附件预览', null, null, () => {
        console.log('success');
    });
    // function(url,name, options, headers, cb)
    // this.getToken().subscribe((token) => {
    //   if (!token) {
    //     return;
    //   }
    //   let url = this.config.getEndpoint('attachmentView') + pdf.attachmentId + "?token=" + token;
    //   InAppBrowserWithHeader.open(url, '附件预览', null, null, () => {
    //     console.log('success');
    //   });
    // });
  }

  private otherPlatform(pdf) {
    let url = 'www.baidu.com';
    let openedDialog = window.open(url, 'pdf 预览');
    if (openedDialog == null || typeof(openedDialog) === 'undefined') {
    location.href = url;
    }
    // this.getToken().subscribe((token) => {
    //   if (!token) {
    //     return;
    //   }
    //   let url = this.config.getEndpoint('attachmentView') + pdf.attachmentId + "?token=" + token;
    //   let openedDialog = window.open(url, 'pdf 预览');
    //   if (openedDialog == null || typeof(openedDialog) == 'undefined') {
    //     location.href = url;
    //   }
    // });
  }

  private android(pdf) {
        DXPDFViewer.openURL();
        //   });
    // this.getToken().subscribe((token) => {
    //   if (!token) {
    //     return;
    //   }
    //   DXPDFViewer.openURL(this.config.getEndpoint('attachmentView') + pdf.attachmentId + "?token=" + token, "PDF预览", () => {
    //   });
    // });
  }

//   private getToken() {
//     return Observable.fromPromise<string>(this.storage.get('access_token'))
//       .map((token) => {
//         if (token) {
//           return this.encrypt.decryptToken(token);
//         } else {
//           return null;
//         }
//       });
//   }

}
